package com.hmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemFeignClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParam;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 搜索栏自动补全功能
     */
    @Override
    public List<String> getSuggestions(String key) {
        try {
            // 1.准备Request，创建请求语义对象
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL，设置自动补全的DSL语句
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",//起个名称（自定义）
                    //自动补全字段（匹配哪个字段）
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key) //传过来的数据
                            .skipDuplicates(true) //跳过重复
                            .size(10) //要多少个数据
            ));
            // 3.发起请求给ES
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据自动补全字段的名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options数组
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项聚合功能
     *  动态获取数据展现在分类标签中
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParam params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1 构建聚合查询语句（聚合方法的调用）
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            // 获取所有的聚合结果
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            //TODO：注意，result map集合中的key必须和前端对应，否则前端解析不了
            result.put("brand", brandList);
            // 4.3.根据分类名称，获取分类结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            // 返回结果
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项聚合功能 - 构建聚合查询语句
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }

    /**
     * 过滤项聚合功能 - 根据聚合名称获取聚合内容
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合内容
        Terms terms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        // 4.3.遍历
        List<String> list = new ArrayList<>();
        if (buckets!=null&&buckets.size()>0) {
            for (Terms.Bucket bucket : buckets) {
                // 4.4.获取key
                String key = bucket.getKeyAsString();
                list.add(key);
            }
        }
        return list;
    }



    /**
     *  基本搜索功能
     * - 关键字搜索
     * - 分类、品牌、价格过滤
     * - 排序
     * - 分页
     * - 高亮
     * - 竞价排名
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParam params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.1 准备DSL(基础的DSL查询语句）

            buildBasicQuery(params,request);

            // 2.2.分页
            int page = Math.toIntExact(params.getPage());
            int size = Math.toIntExact(params.getSize());
            request.source().from((page - 1) * size).size(size);

            // 2.3 高亮 搜索条件->查询结果修改
            request.source().highlighter(new HighlightBuilder().field("all").requireFieldMatch(false));


            //销量降序排序
            /*String sortBy = params.getSortBy();
            if (sortBy != null && !sortBy.equals("")) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("sortBy", new GeoPoint(sortBy))
                        .order(SortOrder.DESC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }*/

            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *   基本搜索功能 - 基础查询SDL语句
     */
    private void buildBasicQuery(RequestParam params, SearchRequest request) {
        //1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.关键字搜索
        String key = params.getKey();
        if (Strings.isNullOrEmpty(key)) {
            //判断Key为空的时候查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            //判断Key不为空的时候根据key查询
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }

        // 分类条件
        if (!Strings.isNullOrEmpty(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 4、.品牌条件
        if (!Strings.isNullOrEmpty(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 6.价格
        if (params.getMinPrice()!=null&&params.getMaxPrice()!=null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        }

        // 算分控制，添加广告标记（竞价排名）
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
    }

    /**
     *   基本搜索功能 - 结果解析
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);

            //TODO：获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    itemDoc.setName(name);
                }
            }

            // 放入集合
            itemDocs.add(itemDoc);
        }
        return new PageDTO<>(total, itemDocs);
    }


    /**
     *  自动注入feign远程调用的客户端对象
     */
    @Autowired
    private ItemFeignClient itemFeignClient;

    /**
     * 监听商品新增或修改的业务
     * @param id item的id
     */
    @Override
    public void insertById(Long id) {
        try {
            // 根据id查询商品信息
            Item iterm = itemFeignClient.getItermById(id);
            // 转化为文档类型
            ItemDoc itemDoc = new ItemDoc(iterm);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 监听商品删除的业务
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
